package kn.pulldata.service.impl;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import kn.pulldata.common.OkHttpUtils;
import kn.pulldata.req.QueryTonalStateReq;
import kn.pulldata.service.ExternalService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.Headers;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ExternalServiceImpl implements ExternalService {


    @Override
    public String queryTonalState(QueryTonalStateReq req, String nextUrl) {


        Headers.Builder headersBuilder = new Headers.Builder();
        headersBuilder.add("Content-Type", "application/x-www-form-urlencoded");

        FormBody.Builder formBuilder = OkHttpUtils.formBodyBuilder()
                .add("title", JSONUtil.toJsonStr(req.getTitle()))
                .add("content", JSONUtil.toJsonStr(req.getContent()));
        try {
            //log.info("调性请求地址：{}",nextUrl);
            String body = OkHttpUtils.postFormWithHeaders(nextUrl, formBuilder, headersBuilder);
            JSONObject obj = JSONUtil.parseObj(body);
            String label = (String) obj.get("label");
            switch (label){
                case "__label__positive":
                    return "0";
                case "__label__unrelated":
                case "__label__neutral":
                    return "1";
                case "__label__negative":
                    return "2";
                default:
                    return "1";
            }
        } catch (Exception e) {
            log.error("调性判断出错：{},异常信息{}",req, e.getMessage());
            e.printStackTrace();
        }
        return "1";
    }

}
